package com.ioidea.ble.proto

import com.ioidea.base.util.MyLogger
import com.ioidea.base.util.Symbol

/**
 *
 * 首次获取白名单
 * request:   @@12233445:WHSGET\r\n
 * response:  ##12233445:WHMULT:000 003 003 A172508548F2 A172497113F2 A172500209F2
 *
 * 下一次是
 * request:   @@12233445:WHMULT\r\n
 * response:  ##12233445:WHMULT:000 003 003 A172508548F2 A172497113F2 A172500209F2
 */
class GetWhiteListProtoBase(override var requestCommand: String="WHSGET",
                            override var responseCommand: String="WHMULT") : ProtoBase() {

    //搜索出来的所有设备 放到List sn里
    val whiteList=WhiteListDev()
    companion object{
        //一次获取的设备数量
        const val ONE_GET_DEV_NUM=10
    }


    /**
     * 获取下一次白名单的payload
     * @param whiteList 上一次返回的数据
     */
    fun  getNextPayload(whiteList: WhiteListDev):String{
        val format="%03d"
        val currentDevNum = String.format(format, whiteList.currentDevNum+ONE_GET_DEV_NUM)
        val devNum = String.format(format, ONE_GET_DEV_NUM)
        val devTotal = String.format(format, whiteList.devTotal)

        val payLoadBuilder=StringBuilder()
        payLoadBuilder.append(currentDevNum).append(Symbol.SPACE)
            .append(devNum).append(Symbol.SPACE)
            .append(devTotal)
        return payLoadBuilder.toString()
    }


    /**
     * 发送结束payload
     *  @param whiteList 上一次返回的数据
     */
    fun  getEndPayload(whiteList: WhiteListDev):String{
        val format="%03d"
        val currentDevNum = String.format(format, whiteList.devTotal)
        val devNum = String.format(format, 0)
        val devTotal = String.format(format, whiteList.devTotal)

        val payLoadBuilder=StringBuilder()
        payLoadBuilder.append(currentDevNum).append(Symbol.SPACE)
            .append(devNum).append(Symbol.SPACE)
            .append(devTotal)
        return payLoadBuilder.toString()
    }

    /**
     * 当前设备个数ID 数倍数量 设备总数 设备SN
     */
    fun parseWhiteResponse(sn: String, wholeData: String) :WhiteListDev {
        //指当前设备个数ID 数倍数量 设备总数 序号
        val headDevNum=3
        //去头尾
        val data = removeHeadTail(wholeData)
        MyLogger.hLog().e("data:$data")
        //后面可以校验数据长度是否正确 暂时让数据有问题的奔溃 发现问题
        val dataArray= data.split(Symbol.SPACE)
        if (dataArray.size>headDevNum){
            whiteList.currentDevNum=dataArray[0].toInt()
            whiteList.devNum=dataArray[1].toInt()//这个代表设备个数
            whiteList.devTotal=dataArray[2].toInt()

            for (index in 0 until whiteList.devNum){
                whiteList.list.add(dataArray[headDevNum+index])
            }
        }else{
            //暂时认为 异常数据就发结束
            whiteList.currentDevNum=whiteList.devTotal
        }
        return whiteList

    }
}

data class WhiteListDev(var currentDevNum:Int=0, var devNum:Int=0, var devTotal:Int=0, var list: ArrayList<String> =ArrayList<String>()){

    fun hasNext():Boolean{
        if (list.size<devTotal){
            return true
        }
        return false
    }

}
